//
//  JSViewController46.swift
//  RXSwiftTest
//
//  Created by ZhangBo on 2019/6/19.
//  Copyright © 2019 ZhangBo. All rights reserved.
//

import UIKit

import RxSwift
import RxCocoa
import RxDataSources
import Alamofire
import RxAlamofire

class JSViewController46: BaseViewController {
    let disposeB = DisposeBag()
    var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        test6()
    }

}

//三、将结果转为 JSON 对象

extension JSViewController46 {
    //1，通过 rx.response 请求数据
    fileprivate func test1() {
        //创建URL对象
        let urlString = "https://www.douban.com/j/app/radio/channels"
        let url = URL(string: urlString)!

        //创建并发起请求
        request(.get, url).data().subscribe(onNext: { data in
            let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]
            print("--- 请求成功！返回的如下数据 ---")
            print(json!)
        }).disposed(by: disposeB)
    }

    fileprivate func test2() {
        //创建URL对象
        let urlString = "https://www.douban.com/j/app/radio/channels"
        let url = URL(string: urlString)!

        //创建并发起请求
        request(.get, url).responseJSON().subscribe(onNext: { dataResponse in
            let json = dataResponse.value as! [String: Any]
            print("--- 请求成功！返回的如下数据 ---")
            print(json)
        }).disposed(by: disposeB)
    }

    fileprivate func test3() {
        //创建URL对象
        let urlString = "https://www.douban.com/j/app/radio/channels"
        let url = URL(string: urlString)!

        //创建并发起请求
        requestJSON(.get, url).subscribe(onNext: { response, data in
            let json = data as! [String: Any]
            print("--- 请求成功！返回的如下数据 ---")
            print(json)
        }).disposed(by: disposeB)
    }
}

extension JSViewController46 {
    fileprivate func test4() {
        //创建表格视图
        self.tableView = UITableView(frame: self.view.frame, style: .plain)
        //创建一个重用的单元格
        self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(self.tableView!)

        //创建URL对象
        let urlString = "https://www.douban.com/j/app/radio/channels"
        let url = URL(string: urlString)!

        //获取列表数据
        let data = requestJSON(.get, url).map { response, data -> [[String: Any]] in
            if let json = data as? [String: Any],
               let channels = json["channels"] as? [[String: Any]] {
                return channels
            } else {
                return []
            }
        }

        //将数据绑定到表格
        data.bind(to: tableView.rx.items) { (tableView, row, element) in
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
            cell.textLabel?.text = "\(row)：\(element["name"]!)"
            return cell
        }.disposed(by: disposeB)
    }


    fileprivate func test5() {
        //创建URL对象
        let urlString = "https://www.douban.com/j/app/radio/channels"
        let url = URL(string: urlString)!

        //创建并发起请求
        requestJSON(.get, url).map {
            $1
        }.mapObject(type: Douban.self).subscribe(onNext: { (douban: Douban) in
            if let channels = douban.channels {
                print("--- 共\(channels.count)个频道 ---")
                for channel in channels {
                    if let name = channel.name, let channelId = channel.channelId {
                        print("\(name) （id:\(channelId)）")
                    }
                }
            }
        }).disposed(by: disposeB)
    }

}

//四，将结果映射成自定义对象
extension JSViewController46 {
    fileprivate func test6() {
        //创建表格视图
        self.tableView = UITableView(frame: self.view.frame, style: .plain)
        //创建一个重用的单元格
        self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(self.tableView!)

        //创建URL对象
        let urlString = "https://www.douban.com/j/app/radio/channels"
        let url = URL(string: urlString)!

        //获取列表数据
        let data = requestJSON(.get, url).map {
            $1
        }.mapObject(type: Douban.self).map {
            $0.channels ?? []
        }

        //将数据绑定到表格
        data.bind(to: tableView.rx.items) { (tableView, row, element) in
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
            cell.textLabel?.text = "\(row)：\(element.name!)"
            return cell
        }.disposed(by: disposeB)
    }

}

